import request from "@/utils/request";

class FileAPI {
  /**
   * 上传文件
   *
   * @param file
   */
  static upload(file: File, content?: string) {
    const formData = new FormData();
    formData.append("file", file);
    if (content) {
      formData.append("content", content);
    }
    return request<any, FileInfo>({
      url: "/store/upload",
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then((res) => {
      if (res.filePath) {
        const path = res.filePath.split("/upload/")[1];
        return { ...res, filePath: `/upload/${path}` };
      }
      return res;
    });
  }
  /**
   * 上传文件
   *
   * @param file
   */
  static uploadLkl(
    file: File,
    content?: string,
    type?: string,
    extra?: object
  ) {
    const formData = new FormData();
    formData.append("file", file);
    if (type) {
      formData.append("attType", type);
    }
    if (content) {
      formData.append("content", content);
    }
    if (extra) {
      Object.keys(extra).forEach((key) => {
        formData.append(key, extra[key]);
      });
    }

    return request<any, FileInfo>({
      url: "/store/uploadLakala",
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then((res) => {
      if (res.filePath) {
        const path = res.filePath.split("/upload/")[1];
        return { ...res, filePath: `/upload/${path}` };
      }
      return res;
    });
  }

  /**
   * 删除文件
   *
   * @param filePath 文件完整路径
   */
  static deleteByPath(filePath?: string) {
    return request({
      url: "/api/v1/files",
      method: "delete",
      params: { filePath: filePath },
    });
  }
}

export default FileAPI;

/**
 * 文件API类型声明
 */
export interface FileInfo {
  //
  id?: number;
  //文件名称
  fileName?: string;
  //上传文件路径
  filePath?: string;
  //创建时间
  createdAt?: string;
  //更新时间
  updatedAt?: string;
}
